package com.zijing2333.adaptivescheduling.SwitcherManager;



import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

import com.zijing2333.adaptivescheduling.criticalNodeJudgment.JudgeKeyNode;
import com.zijing2333.adaptivescheduling.criticalNodeJudgment.JudgeKeyNode1;
import com.zijing2333.servicerunner.JSStatus;

import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskInfoManager {
    //打印log的标记
    private static final String TAG = "fun_TaskInfoManager";
    //线程池对象
    private ExecutorService mExecutorService;

    //存放的是本设备中会运行的JS服务集合，存放的是服务的所有信息
    private ConcurrentHashMap<String, SwitchTaskInfo> taskInfos = new ConcurrentHashMap<>();

    //存放的是本设备中会运行的JS副本任务集合，存放的是服务的所有信息
    private ConcurrentHashMap<String, SwitchTaskInfo> copyInfos = new ConcurrentHashMap<>();

    private JudgeKeyNode judgeKeyNode;






    private static class HOLDER{ //单例的持有类，类一旦加载就创建一个单例
        private static final TaskInfoManager INSTANCE = new TaskInfoManager();
    }


    private TaskInfoManager(){ //无构造方法，申明出一个可缓存的线程池
        mExecutorService = Executors.newCachedThreadPool();
    }

    public static TaskInfoManager getInstance(){
        return TaskInfoManager.HOLDER.INSTANCE;
    }


    //更新Js服务运行集合中的服务状态 -----这块有bug
    public boolean updateTaskStates(Switcher mSwitcher){
        try{
//            Map<String, JSStatus> jsServiceStatusMap = mSwitcher.getJSServiceStatusMap();
            for (String taskID: taskInfos.keySet()) {
//                //调用获取状态的接口
//                JSStatus state = jsServiceStatusMap.get(taskID);
//                if (state !=null){
//                    taskInfos.get(taskID).setState(state);
//                }
                //调用获取状态的接口
                taskInfos.get(taskID).setState(JSStatus.RUNNING);
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //向服务map中增加新服务，同时设置任务的状态为RUNNING,同时设置任务是否是关键节点
    public boolean addTask(SwitchTaskInfo switchTaskInfo){
        try{
            switchTaskInfo.setState(JSStatus.RUNNING);
            Log.d(TAG, "addTask:=======0：setState OK ");
//            switchTaskInfo.setKeyNode(JudgeKeyNode1.getInstance().judge(switchTaskInfo.getPriority()));
            Log.d(TAG, "addTask:=======1：setkeyNode OK-----------判断的结果为："+switchTaskInfo.isKeyNode());
            taskInfos.put(switchTaskInfo.getTaskId(),switchTaskInfo);
            Log.d(TAG, "addTask:=======2：add Map OK ,taskId为："+switchTaskInfo.getTaskId());
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //设置服务状态 NEW 这里就不new了,new的话都放在了addTask方法当中，这里直接从map中取出来
    public boolean setJsState(SwitchTaskInfo switchTaskInfo,JSStatus state) {
        SwitchTaskInfo task = taskInfos.get(switchTaskInfo.getTaskId());
        try {
            task.setState(state);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //移除JS服务
    public boolean removeJsMap(String taskId) {
        if(taskInfos.containsKey(taskId)){
            taskInfos.remove(taskId);
            return true;
        }
        return false;

    }

    //获得正在运行的JS服务map集合
    public Map<String, SwitchTaskInfo> getJsMap() {
        return taskInfos;
    }

    //得到运行状态为RUNNING的任务id的Set集合
    public HashSet<String> getRunningTaskSet(){
        HashSet<String> runningSet = new HashSet<>();
        try {
            for(String id:taskInfos.keySet()){
                if("RUNNING".equals(taskInfos.get(id).getState())){
                    runningSet.add(id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return runningSet;
    }

    //得到运行状态为RUN_COMPLETED的任务id的Set集合
    public HashSet<String> getRunCompletedTaskSet(){
        HashSet<String> RunCompletedSet = new HashSet<>();
        try {
            for (String id:taskInfos.keySet()){
                if ("RUN_COMPLETED".equals(taskInfos.get(id).getState())){
                    RunCompletedSet.add(id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return RunCompletedSet;
    }

    //-------------------以下均为新增 NEW
    //设置任务的sourceIP（源IP）属性，这个属性只在副本任务中存
    public boolean setCopySourceIp(String taskInfoId,String soureceIp){
        SwitchTaskInfo task = copyInfos.get(taskInfoId);
        try {
            task.setSourceIP(soureceIp);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    //向副本map中增加新服务 同时设置副本的状态为WAITING
    public boolean addCopy(SwitchTaskInfo switchTaskInfo){
        try{
            switchTaskInfo.setState(JSStatus.CODE_DOWNLOADED);
            copyInfos.put(switchTaskInfo.getTaskId(),switchTaskInfo);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    //获得正在运行的JS副本服务map集合
    public Map<String, SwitchTaskInfo> getCopyMap() {
        return copyInfos;
    }

    //移除副本JS服务
    public boolean removeCopyMap(String taskId) {
        if(taskInfos.containsKey(taskId)){
            copyInfos.remove(taskId);
            return true;
        }
        return false;
    }

    //得到副本Map中指定任务id的原始TaskInfo类
    public SwitchTaskInfo getTaskInfoInCopy(String taskId){
        return copyInfos.get(taskId);
    }

    //得到正在设备上存着的副本任务id集合
    public HashSet<String> getCopyTaskSet(){
        HashSet<String> waitingSet = new HashSet<>();
        try {
            for(String id:copyInfos.keySet()){
                if(copyInfos.get(id).getState()==JSStatus.CODE_DOWNLOADED){
                    waitingSet.add(id);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return waitingSet;
    }

    //设置副本服务状态
    public boolean setCopyState(SwitchTaskInfo switchTaskInfo,JSStatus state) {
        SwitchTaskInfo task = copyInfos.get(switchTaskInfo.getTaskId());
        try {
            task.setState(state);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //设置socket建立的类型，type=0表示该任务未建立socket，=1表示任务建立在客户端socket上，=2表示任务建立在服务端socket上
    public void setSocketEstablishType(String taskId,int type){
        try {
            if (taskInfos.get(taskId) == null){
                Log.d(TAG, "setSocketEstablishType: =================1  taskInfo中的任务信息对象为空");
            }
            taskInfos.get(taskId).setSocketEstablishType(type);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public int getSocketEstablishType(String taskId){
        SwitchTaskInfo task = taskInfos.get(taskId);
        return task.getSocketEstablishType();
    }
}
